{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "43cea4f8",
   "metadata": {},
   "source": [
    "# Async LLMPredictor Demo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6d46041",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.langchain_helpers.chain_wrapper import LLMPredictor\n",
    "from llama_index.prompts.default_prompts import DEFAULT_SUMMARY_PROMPT\n",
    "import asyncio\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19e0b5e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "context_strs = [\n",
    "    \"Paul Graham\",\n",
    "    \"Steve Jobs\",\n",
    "    \"Barack Obama\",\n",
    "]\n",
    "\n",
    "prompt = DEFAULT_SUMMARY_PROMPT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "884c9df3",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = LLMPredictor()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c5b368b",
   "metadata": {},
   "source": [
    "#### By default, LLM calls are blocking (i.e. only one API request at a time)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26ed839a",
   "metadata": {},
   "outputs": [],
   "source": [
    "start_time = time.perf_counter()\n",
    "outputs = [llm.predict(prompt, context_str=context_str) for context_str in context_strs]\n",
    "elapsed_time = time.perf_counter() - start_time"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9bc08db7",
   "metadata": {},
   "source": [
    "It takes ~19s to finish all 3 calls."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dba14b97",
   "metadata": {},
   "source": [
    "#### We can enable asynchronous calls with the `apredict` function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb007b19",
   "metadata": {},
   "outputs": [],
   "source": [
    "start_time = time.perf_counter()\n",
    "tasks = [llm.apredict(prompt, context_str=context_str) for context_str in context_strs]\n",
    "await asyncio.gather(*tasks)\n",
    "elapsed_time = time.perf_counter() - start_time"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efb77aa3",
   "metadata": {},
   "source": [
    "It takes ~7s to finish all 3 calls."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
